task("xcframework")
set_category("plugin")

local pari = {
  iphoneos = { "arm64",  },
  watchos = { "arm64_32", "armv7k" },
  appletvos = { "arm64" },
  iphonesimulator = { "arm64", "x86_64" },
  watchsimulator = { "arm64", "x86_64" },
  appletvsimulator = { "arm64", "x86_64" },
  macosx = { "x86_64" },
}

set_menu({
  usage = "xmake xcframework [platform] [arch]",
  description = "build xcframework",
  options = {}
})

local function printTable(t, indent)
  indent = indent or 0
  local indentStr = string.rep("  ", indent)
  
  if type(t) ~= "table" then
      print(indentStr .. tostring(t))
      return
  end

  print(indentStr .. "{")
  for k, v in pairs(t) do
      local keyStr = tostring(k)
      if type(v) == "table" then
          print(indentStr .. "  " .. keyStr .. " = ")
          printTable(v, indent + 1)
      else
          local valueStr = tostring(v)
          print(indentStr .. "  " .. keyStr .. " = " .. valueStr)
      end
  end
  print(indentStr .. "}")
end

on_run(function ()
  import("core.base.option")
  import("core.project.project")
  import("core.tool.toolchain")
  
  local output_dir = path.join(os.curdir(), "build", "xcframework")
  os.mkdir(output_dir)

  local frameworks = {}
  for _, arch in ipairs(pari['iphoneos']) do
    table.insert(frameworks, " -framework " .. path.join("build/iphoneos", arch, "release/qjs.framework"))
  end
  for _, arch in ipairs(pari['macosx']) do
    table.insert(frameworks, " -framework " .. path.join("build/macosx", arch, "release/qjs.framework"))
  end

  printTable(frameworks)
  print(table.concat(frameworks, " "))
  local xcframework_path = path.join(output_dir, "qjs.xcframework")
  os.execv("xcodebuild -create-xcframework -output " .. xcframework_path .. " " .. table.concat(frameworks, " ") )
  print("🌹XCFramework created at: " .. xcframework_path)
end)